package com.changgou.search.service.impl;

import changgou.itheima.service.SkuInfo;
import com.alibaba.fastjson.JSON;
import com.changgou.entity.Result;
import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.pojo.Sku;
import com.changgou.search.dao.ESManagerMapper;
import com.changgou.search.service.ESManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class ESManagerServiceImpl implements ESManagerService {
    @Autowired
    private ESManagerMapper esManagerMapper;

    @Autowired
    private SkuFeign skufeign;

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    /**
     * 创建索引映射
     */
    @Override
    public void createIndexAndMapping() {
        elasticsearchTemplate.createIndex(SkuInfo.class);
        elasticsearchTemplate.putMapping(SkuInfo.class);
    }

    @Override
    public void importAll() {
        ExecutorService executorService = Executors.newFixedThreadPool(9);
        Integer count = skufeign.countSku();
        Integer pageSize = 2500;
        Integer pageTotal = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
//        CountDownLatch cdl = new CountDownLatch(pageTotal);
        long l = System.currentTimeMillis();
        for (Integer i = 0; i < pageTotal; i++) {
            executorService.execute(new importData4Page(i + 1, pageSize));
        }
       /* try {
            cdl.await();
            long l1 = System.currentTimeMillis();
            System.out.println(l1-l);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/

    }

    class importData4Page implements Runnable {
        int page;
        int size;
        CountDownLatch cdl;

        public importData4Page(int page, int size) {
            this.page = page;
            this.size = size;
        }

        public importData4Page(int page, int size, CountDownLatch cdl) {
            this.page = page;
            this.size = size;
            this.cdl = cdl;
        }

        @Override
        public void run() {
            //分页查询sku数据
            //查询条件
            HashMap<String, Object> map = new HashMap<>();
            map.put("status", "1");
            Result result = (Result) skufeign.findPage(map, this.page, size);
            Map pageResult = (Map) result.getData();
            List rows = (List) pageResult.get("rows");
            if (result.isFlag() && rows != null && rows.size() > 0) {
                List<SkuInfo> list = skuList2SkuinfoList(rows);
                esManagerMapper.saveAll(list);
            } else {
                throw new RuntimeException("第" + this.page + "页sku数据分页查询失败");
            }
            if (cdl!=null) cdl.countDown();
            System.out.println("第" + Thread.currentThread().getName() + "个进程成功执行");
        }
    }


    @Override
    public void importData2ESBySpuId(String spuId) {
        //查询spuid对应的所有sku
        List<Sku> skus = skufeign.fingListBySpuId(spuId);
        if (skus == null && skus.size() <= 0) {
            throw new RuntimeException("当前商品无数据，无法导入索引库");
        }
        List<SkuInfo> skuInfoList = skuList2SkuinfoList(skus);
        //导入索引库
        esManagerMapper.saveAll(skuInfoList);
        skus.forEach(sku -> System.out.println("添加了："+sku.getId()));
    }

    @Override
    public void deleteData2ESBySpuId(String spuid) {
        //查询spuid对应的所有sku
        List<Sku> skus = skufeign.fingListBySpuId(spuid);
        skus.forEach(sku ->  esManagerMapper.deleteById(Long.valueOf(sku.getId())));
        skus.forEach(sku -> System.out.println("删除了："+sku.getId()));
    }

    private List<SkuInfo> skuList2SkuinfoList(List<Sku> skus) {
        //将数据转化为json
        String json = JSON.toJSONString(skus);
        //将json转化为索引库对象
        List<SkuInfo> skuInfoList = JSON.parseArray(json, SkuInfo.class);
        //将规格转化为规格参数
        for (SkuInfo skuInfo : skuInfoList) {
            String spec = skuInfo.getSpec();
            Map map = JSON.parseObject(spec, Map.class);
            skuInfo.setSpecMap(map);
        }
        return skuInfoList;
    }
}
